import { killTCP, run, killPID, LOG } from 'koagun'
import { getDefaultConfig } from './config/app_default.cfg'
import { getBuildConfig } from './config/app_build.cfg'
import { createApp } from './src/app'
import { program } from 'commander'
import _ from 'lodash'


async function runApp(path: string) {
  run(`node --es-module-specifier-resolution=node ${path}`, {
    env: { NODE_ENV: 'production', ...process.env }
  })
}

program.name('CLI')

program.command('prod')
  .description('run in production env')
  .action(async function() {
    const config = getDefaultConfig()
    try {
      await runApp('build/tsc/src/index.js')
    } catch (e) {
      killTCP(config.LISTEN_PORT)
      await runApp('build/tsc/src/index.js')
    }
  })

program.command('prod-queue')
  .description('run queue in production env')
  .action(async function() {
    await runApp('build/tsc/src/queue.js')
  })

program.command('dev')
  .description('for develop with nodemon')
  .action(async function() {
    run('npx nodemon -e ts --exec npm run tsc && node --es-module-specifier-resolution=node build/tsc/src/index.js', {
      env: { NODE_ENV: 'local' }
    })
  })

program.command('kill')
  .description('eg: npm run kill -- --port=80')
  .description('kill the running port')
  .action(async function() {
    let config = getDefaultConfig()
    if (config.ENV === 'local') {
      // @ts-ignore
      config = (await import('../config/app_local.cfg')).getLocalConfig()
    }
    for(let i = 0 ; i <= config.CPUS ; i++) {
      killTCP(config.LISTEN_PORT + i)
    }
  })

program.command('build')
  .description('build html and css')
  .action(async function() {
    const app = await createApp(getBuildConfig())
    await app.vite.build()
    process.exit(0)
  })

program.parse()